/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.product;

import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.persistence.Parameter;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.modules.ivm.dao.product.ProductOutDetailDao;
import com.neusoft.lohas.modules.ivm.entity.product.ProductOutDetail;

/**
 * 商品出库记录Service
 * @author Jackie.Liu
 * @version 2014-12-30
 */
@Component
@Transactional(readOnly = true)
public class ProductOutDetailService extends BaseService {

	@Autowired
	private ProductOutDetailDao productOutDetailDao;
	
	public ProductOutDetail get(String id) {
		return productOutDetailDao.get(id);
	}
	
	public Page<ProductOutDetail> find(Page<ProductOutDetail> page, ProductOutDetail productOutDetail) {
		DetachedCriteria dc = productOutDetailDao.createDetachedCriteria();
		dc.add(Restrictions.eq(ProductOutDetail.FIELD_DEL_FLAG, ProductOutDetail.DEL_FLAG_NORMAL));
		dc.add(Restrictions.eq("product.id", productOutDetail.getProduct().getId()));
		dc.addOrder(Order.asc("createDate"));
		return productOutDetailDao.find(page, dc);
	}
	
	public Page<Map<String, Object>> findInOut(Page<Map<String, Object>> page, String productId, String startDate, String endDate) {
		String sql = "SELECT 1 as inOrOut,a.create_date as create_date, a.product_id as product_id, 0 as stock, a.win_weight as inNum, 0 as outNum, 0 as outType, 0 as endTock " +
					"FROM ivm_product_inventory_detail a WHERE a.product_id = :p1 UNION ALL " +
					"SELECT 2 AS inOrOut, b.create_date AS create_date, b.product_id AS product_id, 0 as stock, 0 AS inNum, b.weight AS outNum, b.type AS outType, 0 as endTock " +
					"FROM ivm_product_out_detail b WHERE b.product_id = :p2 ORDER BY create_date ASC";
		return productOutDetailDao.findBySql(page, sql, new Parameter(productId,productId), Map.class);
	}
	
	@Transactional(readOnly = false)
	public void save(ProductOutDetail productOutDetail) {
		productOutDetailDao.save(productOutDetail);
	}
	
	@Transactional(readOnly = false)
	public void save(List<ProductOutDetail> list) {
		productOutDetailDao.save(list);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		productOutDetailDao.deleteById(id);
	}

}
